package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import com.alipay.zxy.alipayplugin.message.response.AlipayTradeQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zxy
 */
@Slf4j
@Service
public class AlipayTradePayQueryService extends BaseService {
    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayTradePayQueryService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipayTradeQueryDTO query(AlipayTradeQueryModel alipayModel) throws AlipayApiException {
        AlipayTradeQueryDTO tradeQueryDTO;
        if (StringUtils.isNotBlank(alipayModel.getTradeNo()) || StringUtils.isNotBlank(alipayModel.getOutTradeNo())) {
            log.error("缺少必要参数支付宝订单号或商户订单号");
            return null;
        }
        //初始化请求类
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest = (AlipayTradeQueryRequest) getAlipayRequest(alipayRequest, alipayConfig, alipayModel);
        log.info("支付宝请求参数alipayRequest：{}", alipayRequest);
        //sdk请求客户端，已将配置信息初始化
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        //因为是接口服务，使用exexcute方法获取到返回值
        AlipayTradeQueryResponse alipayResponse = alipayClient.execute(alipayRequest);
        if (alipayResponse.isSuccess()) {
            log.info("统一收单线下交易查询接口调用成功 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            tradeQueryDTO = new AlipayTradeQueryDTO();
            tradeQueryDTO.setOutTradeNo(alipayResponse.getOutTradeNo());
            tradeQueryDTO.setSendPayDate(alipayResponse.getSendPayDate().getTime() / 1000L);
            tradeQueryDTO.setTotalAmount(alipayResponse.getTotalAmount());
            tradeQueryDTO.setTradeNo(alipayResponse.getTradeNo());
            tradeQueryDTO.setTradeStatus(alipayResponse.getTradeStatus());
            return tradeQueryDTO;
        } else {
            log.info("统一收单线下交易查询接口调用失败 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return null;
        }
    }
}
